{% include 'pioneer-private/header.html' %}
<div id="search_box" class="default">
	<select id="search_mode" >
		<option value="title">{{ ui.search_form_mode_title }}</option>
		<option value="tindes">{{ ui.search_form_mode_tindes }}</option>
		<option value="tagx">{{ ui.search_form_mode_tag }}</option>
		<option style="display: none;" value="tag">STAG (LEGACY)</option>
	</select>
	<div id="search_wrap">
		<input id="search_value" />
		<button id="search_do">{{ ui.search_form_do }}</button>
	</div>
	<a href="search_help.html">{{ ui.search_help_link }}</a>
</div>
<div id="search_info" class="default">

</div>
<div class="items">
	<div class="item hide">
		<picture class="_thumbnail">
		</picture>
		<div class="content">
			<div class="name"><a href="#" class="name_a"></a></div>
			<div class="description"></div>
		</div>
	</div>
	<div style="height: 20px;"></div>
</div>
<div class="default">
{% include 'pioneer-private/copying.html' %}
</div>
<script src="{{ res(rr, [ 'scripts', 'base.js' ]) }}"></script>
<script src="{{ res(rr, [ 'scripts', 'searchexpr.js' ]) }}"></script>
{% if args.file_uri_workaround %}
<script src="{{ res(rr, [ 'scripts', 'searchdb_offline.js' ], force_ignore_file_check = True) }}"></script>
{% endif %}
<script>
const items = $('.items');
const template = $('.item');

const query = window.location.search.substring(1);
const mode = query.substring(0, query.indexOf('?'));
let value = decodeURIComponent(query.substring(query.indexOf('?') + 1));

let getL10n = (game, property) => {
	return (game.tr.hasOwnProperty("{{ lang }}") &&
		game.tr["{{ lang }}"].hasOwnProperty(property)) ?
		game.tr["{{ lang }}"][property] : game[property];
}

let add = (id, game) => {
	const item = template.cloneNode(true);
	item.classList.remove("hide");

	const _prefix = "{{ res(rr, ['']) }}"
	const thumb = item.querySelector("._thumbnail");

	make_picture(game.thumbnail, _prefix, thumb);
	thumb.srcNode.classList.add("thumbnail")

	const link = item.querySelector(".name_a");
	link.textContent = getL10n(game, "name");
	link.href = "games/" + id + ".html";

	let desc = getL10n(game, "description");
	if (desc.length > 480)
		desc = desc.substr(0, 480) + "...";
	item.querySelector(".description").textContent = desc;

	items.appendChild(item);
}

const searchTagWithoutNamespace = (searchdb, tag) => {
	let res = new Set(),
		ns = searchdb.tagns[tag];

	if (ns == null)
		ns = [ "author" ];

	ns.forEach(i => {
		console.log(i)
		const tmp = searchdb.rtag[i + ":" + tag] || [];
		res = new Set([...res, ...tmp]);
	});

	return [...res];
}

let onload = async () => {
	$('#search_mode').value = mode;
	if ($('#search_mode').selectedIndex < 0)
		$('#search_mode').selectedIndex = 0;
	$('#search_value').value = value;

	try {
		if (mode !== "")
			$("#search_info").textContent = "{{ ui.search_searching }}";

		let searchdb;
		if (typeof(_searchdb) === 'undefined') {
			searchdb = await (await fetch("{{ res(rr, [ 'scripts', 'searchdb.json' ], force_hc_uquery=time()|int) }}")).json();
		} else {
			searchdb = _searchdb;
		}

		let num = 0;

		switch (mode) {
		case "tag":
			if (searchdb.rtag.hasOwnProperty(value)) {
				const res = searchdb.rtag[value];
				res.forEach(i => add(i, searchdb.data[i]));
			} else {
				items.textContent = "{{ ui.search_not_found }}";
			}
			break;
		case "tagx":
			searchexpr(value, ((tag, args) => {
				console.log("find: " + tag);
				switch (tag) {
				case '$all':
					return Object.keys(searchdb.data);
					break;
				case '$sortcmpr':
					switch (args.sortedBy) {
					case "lastmod":
						return searchdb.data[args.secondElm].mtime - searchdb.data[args.firstElm].mtime;
						break;
					default:
						throw "unknown sortedBy arg: " + args.sortedBy;
						break;
					}
				}

				let ns = tag.substring(0, tag.indexOf(":"))
				let v = tag.substring(tag.indexOf(":") + 1)

				if (searchdb.tagalias.hasOwnProperty(v)) {
					v = searchdb.tagalias[v];
				}

				switch (ns) {
				case 'malex':
					ns = 'male';
					break;
				case 'femalex':
					ns = 'female';
					break;
				case '':
					return searchTagWithoutNamespace(searchdb, v);
					break;
				}

				tag = ns + ":" + v;

				return searchdb.rtag[tag] || [];
			})).forEach(i => {
				num++;
				add(i, searchdb.data[i])
			});

			$("#search_info").textContent = "{{ ui.search_found_n_item }}".format(num);
			break;
		case "title":
		case "tindes":
			value = value.toLowerCase();
			for (const [id, game] of Object.entries(searchdb.data)) {
				console.log(id);
				if (game.name.toLowerCase().indexOf(value) >= 0) {
					num++;
					add(id, game);
					continue;
				}

				if (mode === "tindes" && game.description.toLowerCase().indexOf(value) >= 0) {
					num++;
					add(id, game);
					continue;
				}

				for (const [lang, l10n] of Object.entries(game.tr)) {
					console.log(lang);
					if (l10n.hasOwnProperty('name') && l10n.name.toLowerCase().indexOf(value) >= 0) {
						num++;
						add(id, game);
						break;
					}

					if (mode === "tindes" &&
						l10n.hasOwnProperty("description") &&
						l10n.description.toLowerCase().indexOf(value) >= 0) {
						num++;
						add(id, game);
						break;
					}
				}
			}

			$("#search_info").textContent = "{{ ui.search_found_n_item }}".format(num);
			break;
		default:
			break;
		}
	} catch (e) {
		$("#search_info").textContent = "Sorry, an error occured.\n" + e;
		console.error(e);
		alert("{{ ui.search_load_db_error }}");
	}
}

let do_search = () => {
	window.location.href = "search.html?" + $('#search_mode').value + "?" + $('#search_value').value
}

$('#search_do').addEventListener('click', e => {
	do_search();
});

$('#search_value').addEventListener('keyup', e => {
	if (e.keyCode == 13)
		do_search();
});

onload();
</script>
{% include 'pioneer-private/footer.html' %}
